﻿using Newtonsoft.Json;
using RuYiAdmin.Net.UniversalFoundation.Configurations;
using RuYiAdmin.Net.UniversalFoundation.Contexts;
using RuYiAdmin.Net.UniversalFoundation.Exceptions.Framework;
using RuYiAdmin.Net.UniversalFoundation.GeneralFoundationClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.UniversalFoundation.Utils
{
    /// <summary>
    /// OpenIM工具类
    /// </summary>
    public class RuYiOpenIMUtil
    {
        #region 获取管理员口令

        /// <summary>
        /// 获取管理员口令
        /// </summary>
        /// <returns></returns>
        /// <exception cref="RuYiAdminCustomException"></exception>
        public static async Task<string> GetToken()
        {
            string token = string.Empty;
            string key = RuYiGlobalConfig.OpenIMConfig.RedisKey;

            if (RuYiRedisContext.Exists(key))
            {
                var adminLoginResInfo = RuYiRedisContext.Get<OpenIMAdminLoginResInfo>(key);
                token = adminLoginResInfo.Data.AdminToken;
            }
            else
            {
                string openIMServerUrl = RuYiGlobalConfig.OpenIMConfig.OpenIMServerUrl;
                string account = RuYiGlobalConfig.OpenIMConfig.Account;
                string password = RuYiGlobalConfig.OpenIMConfig.Password;

                var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(5);
                httpClient.DefaultRequestHeaders.Add(RuYiGlobalConfig.OpenIMConfig.Header0, Guid.NewGuid().ToString());// 设置请求头


                var param = new Dictionary<string, string>();
                param.Add("account", account);
                param.Add("password", password);

                var content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync($"{openIMServerUrl}/account/login", content);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    var adminLoginResInfo = JsonConvert.DeserializeObject<OpenIMAdminLoginResInfo>(result);
                    if (adminLoginResInfo.ErrCode.Equals(0))
                    {
                        RuYiRedisContext.Set(key, adminLoginResInfo, 30);// 将token存入Redis缓存
                        token = adminLoginResInfo.Data.AdminToken;
                    }
                    else
                    {
                        throw new RuYiAdminCustomException($"OpenIM server error: {adminLoginResInfo.ErrMsg}");
                    }
                }
                else
                {
                    throw new RuYiAdminCustomException("Failed to retrieve token from OpenIM server.");
                }
            }
            return token;
        }

        #endregion

        #region 同步用户信息

        /// <summary>
        /// 同步用户信息
        /// </summary>
        /// <param name="users">用户信息</param>
        /// <returns></returns>
        /// <exception cref="RuYiAdminCustomException"></exception>
        public static async Task SyncUserInfo(List<OpenIMUserInfo> users)
        {
            if (users.Count > 0)
            {
                string token = await RuYiOpenIMUtil.GetToken();
                if (string.IsNullOrEmpty(token))
                {
                    throw new RuYiAdminCustomException("Failed to retrieve OpenIM token.");
                }

                string openIMServerUrl = RuYiGlobalConfig.OpenIMConfig.OpenIMServerUrl;

                var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(5);
                httpClient.DefaultRequestHeaders.Add(RuYiGlobalConfig.OpenIMConfig.Header0, Guid.NewGuid().ToString());// 设置请求头
                httpClient.DefaultRequestHeaders.Add(RuYiGlobalConfig.OpenIMConfig.Header1, token);// 设置请求头

                var param = new Dictionary<string, List<OpenIMUserInfo>>();
                param.Add("users", users);

                var content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync($"{openIMServerUrl}/user/import/json", content);

                if (!response.IsSuccessStatusCode)
                {
                    throw new RuYiAdminCustomException("Failed to sync user info with OpenIM server.");
                }
            }
        }

        #endregion
    }
}
